import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Modal, Transfer, Radio, message, Alert, Tabs, Upload, Icon} from 'antd'
const { TabPane } = Tabs;
import SearchArea from 'components/search-area'
import creditModelService from 'containers/credit-setting/credit-model/credit-model.service'
const confirm = Modal.confirm;
const RadioGroup = Radio.Group;
import errorMessage from 'share/errorMessage'
import Importer from 'components/template/importer';
import config from "config";
import ResizeTable from 'components/resize-table';

class CreditModelRange extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      searchForm: [{
        type: 'input', id: 'keyword', label: messages('credit-setting.key34')/*公司代码/公司名称*/
      }],
      columns: [{
        title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 48
      },{
        title: messages('credit-setting.key35')/*公司代码*/, dataIndex: 'companyCode'
      },{
        title: messages('credit-setting.key36')/*公司名称*/, dataIndex: 'name'
      },{
        title: messages("common.operation"),//"操作",
        dataIndex: "operation",
        render: (text, record) => (
          <span>
              <a onClick={() => this.remove(record)}>
                {messages("common.delete")}
              </a>
          </span>
        )
      }],
      loading: false,
      data: [],
      searchParams: {},
      showAssign: false,
      company: [],
      selectedCompanyKey: [],
      assigning: false,
      persist: 'false',
      showImportModal: false,
      downloading: false,
      fileList: [],
      disabled :false
    };
  }

  componentWillMount(){
    creditModelService.getCreditValid(this.props.creditModel.id)  // true失效 false有效
      .then(res => {
        this.setState({ disabled: res.data })
    });
    this.getList(true);
  }

  getList = reset => {
    const { searchParams } = this.state;
    this.setState({ loading: true });
    let services = [creditModelService.getCreditCompany(this.props.creditModel.id, searchParams)];
    if(reset){
      services.push(creditModelService.getUnselectedCompany(this.props.creditModel.id))
    }
    Promise.all(services).then(res => {
      let data = res[0].data;
      data.map((item, index) => {
        item.index = index + 1;
      });
      if(reset){
        this.setState({
          data,
          loading: false,
          company: res[1].data
        })
      } else {
        this.setState({
          data,
          loading: false
        })
      }
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ loading: false });
    })
  };

  search = result => {
    this.setState({ searchParams: result }, this.getList);
  };

  clear = () => {
    this.setState({ searchParams: {} }, this.getList);
  };

  remove = record => {
    const { persist } = this.state;
    confirm({
      title: messages('credit-setting.key37')/*即将从该模型中移除，请确认是否保留现有信用分值？*/,
      content: (
        <RadioGroup onChange={e => this.setState({ persist: e.target.value })} defaultValue={persist}>
          <Radio value="false">{messages('credit-setting.key96')/*不保留*/}</Radio>
          <Radio value="true">{messages('credit-setting.key97')/*保留*/}</Radio>
        </RadioGroup>
      ),
      okText: messages('credit-setting.key20')/*确认*/,
      okType: 'danger',
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        const { persist } = this.state;
        this.setState({ loading: true });
        creditModelService.assignCompany(this.props.creditModel.id,
          {
            companyOIDs: [],
            removeCompanyMap: {
              [record.companyOID]: persist === 'true'
            }
          }
        ).then(res => {
          this.setState({ loading: false, persist: 'false' });
          this.getList(true);
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response);
        });
      },
      onCancel: () => {
        this.setState({ persist: 'false' });
      },
    });
  };

  handleAssign = () => {
    const { selectedCompanyKey } = this.state;
    this.setState({ assigning: true });
    creditModelService.assignCompany(this.props.creditModel.id, {companyOIDs: selectedCompanyKey}).then(res => {
      this.setState({ showAssign: false, assigning: false });
      this.getList(true);
    }).catch(e => {
      this.setState({ assigning: false });
      errorMessage(e.response);
    });
  };

  handleChange = selectedCompanyKey => {
    this.setState({ selectedCompanyKey });
  };

  beforeUpload = (file) => {
    if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
      const isLtSize = file.size / 1024 / 1024 <= 2;
      if (!isLtSize) {
        message.error(messages('components.key893', { arg1: 2 })/*文件不能超过{arg1}M*/);
      } else {
        this.setState({ fileList: [file] });
      }
    } else {
      message.error(messages('setting.key378'/*请上传Excel文件*/));
    }
  };

  render() {
    const { searchForm, columns, loading, data, showAssign, assigning, company, selectedCompanyKey, disabled, persist, downloading, fileList } = this.state;
    return (
      <div>
        <SearchArea searchForm={searchForm}
                    clearHandle={this.clear}
                    submitHandle={this.search} />
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${data.length}`})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button type="primary" onClick={() => this.setState({ showAssign: true })}>{messages('credit-setting.key38')/*分配公司*/}</Button>
            <Button type="primary" disabled={disabled} onClick={() => this.setState({ showImportModal: true })}>{messages('credit-setting.key102')/*初始化导入*/}</Button>
          </div>
        </div>
        <ResizeTable
          columns={columns}
          size="middle"
          bordered
          rowKey="id"
          loading={loading}
          dataSource={data}/>
        <Modal visible={showAssign}
               confirmLoading={assigning}
               title={messages('credit-setting.key38')/*分配公司*/}
               onCancel={() => this.setState({ showAssign: false })}
               onOk={this.handleAssign}>
          <Transfer
            className="common-transfer"
            dataSource={company}
            showSearch
            targetKeys={selectedCompanyKey}
            onChange={this.handleChange}
            render={item => item.name}
            rowKey={record => record.companyOID}
            listStyle={{
              height: 400
            }}
            searchPlaceholder={messages('common.search')}
            notFoundContent={messages('common.no.data')}
          />
        </Modal>
        <Importer
          visible={this.state.showImportModal}
          title={messages('credit-setting.key102')/*初始化导入*/}
          templateUrl={`${config.baseUrl}/api/credit/user/template/export`}
          uploadUrl={`${config.baseUrl}/api/credit/user/score/import`}
          uploadParams={{ modelId: this.props.creditModel.id }}
          errorUrl={`${config.baseUrl}/api/credit/failed/export`}
          listenUrl={`${config.baseUrl}/api/batch/transaction/logs/credit/user`}
          fileName={messages('credit-setting.key103')/*电子表格*/}
          haveConfirm
          downFileName={messages('credit-setting.key104')/*员工初始信用分导入模板*/}
          onOk={this.importOfferFile}
          afterClose={() => this.setState({ showImportModal: false })}
        />
      </div>
    )
  }
}

CreditModelRange.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    creditModel: state.creditSetting.creditModel
  }
}

export default connect(mapStateToProps)(CreditModelRange)
